package com.mgq.netty.c9;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author MaGuangQi
 * @description: 使用netty提供的FixedLengthFrameDecoder解析器
 * {@link FixedLengthFrameDecoder}
 * 服务端和客户端约定最大长度.就可以解决
 * 缺点: 不够灵活,需要先确定最大长度,一旦有超过最大长度,就会产生错误
 * @date 2021-12-06 14:45
 **/
@Slf4j
public class SecondSolutionServer {
    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss, worker);
            serverBootstrap.channel(NioServerSocketChannel.class);
            ChannelFuture future = serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {

                @Override
                protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                    //约定最大长度为16,注意LoggingHandler放到后面,因为inBound是从前到后
                    nioSocketChannel.pipeline().addLast(new FixedLengthFrameDecoder(16));
                    nioSocketChannel.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                }
            }).bind(8080).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("server error", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
